package com.demo.component.multids;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Author DongXL
 * @Create 2018-01-09 21:36
 */

@Configuration
@EnableJpaRepositories(
        basePackages = "com.demo.repository.baoxian",
        entityManagerFactoryRef = "entityManagerFactoryBaoxian",
        transactionManagerRef = "transactionManagerBaoxian")
public class BaoxianDataSourceConfiguration {

    @Resource
    private JpaProperties jpaProperties;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.baoxian")
    public DataSource dataSourceBaoxian() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBaoxian(EntityManagerFactoryBuilder builder, @Qualifier("dataSourceBaoxian") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages(new String[]{"com.demo.model.entity.baoxian", "com.demo.model.entity.tob"})
                .properties(jpaProperties.getHibernateProperties(dataSource))
                .persistenceUnit("baoxian")
                .build();
    }


    @Bean
    PlatformTransactionManager transactionManagerBaoxian(@Qualifier("entityManagerFactoryBaoxian") LocalContainerEntityManagerFactoryBean entityManagerFactoryBaoxian) {
        return new JpaTransactionManager(entityManagerFactoryBaoxian.getObject());
    }
}
